package com.fyt.algorithm.Leecode.day4;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 15. 三数之和
 */
public class ThreeSum {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            if(i > 0 && nums[i -1] == nums[i])
                continue;
            int left = i + 1;
            int right = nums.length - 1;
            int target = 0 - nums[i];
            while (left < right) {

                if (nums[left] + nums[right] == target) {
                    List<Integer> list = new ArrayList();
                    list.add(nums[i]);
                    list.add(nums[left]);
                    list.add(nums[right]);
                    res.add(list);
                    left++;
                    right--;
                    while (left<right&&nums[left] == nums[left - 1])
                        left++;
                    /*while (left<right&&nums[right] == nums[right + 1])
                        right--;*/
                }
                if (nums[left] + nums[right] > target) {
                    right--;
                }
                if (nums[left] + nums[right] < target) {
                    left++;
                }

            }

        }
        return res;
    }
    public static void main(String[] args) {

    }
}
